package com.iwithlong.service.impl;

import com.imesne.assistant.common.bean.BeanKit;
import com.imesne.assistant.common.exception.ImesneException;
import com.imesne.assistant.common.page.PageList;
import com.imesne.assistant.common.utils.EncryptUtils;
import com.imesne.assistant.common.validation.Verifier;
import com.imesne.assistant.jdbc.command.entity.Delete;
import com.iwithlong.context.Constants;
import com.iwithlong.entity.ActivityEnroll;
import com.iwithlong.enums.MemberType;
import org.apache.commons.lang3.StringUtils;
import com.imesne.assistant.jdbc.command.entity.Select;
import com.imesne.assistant.jdbc.persist.JdbcDao;
import com.iwithlong.entity.Merchant;
import com.iwithlong.service.MerchantService;
import com.iwithlong.vo.MerchantVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by mhy on 2018/4/25.
 */
@Service
@Transactional
public class MerchantServiceImpl implements MerchantService {
    @Resource
    private JdbcDao jdbcDao;

    @Override
    public PageList<MerchantVo> pageList(MerchantVo merchantVo) {
        Select<Merchant> merchantSelect = jdbcDao.createSelect(Merchant.class).where("1",1);
        if(StringUtils.isNotBlank(merchantVo.getAccountCode())){
            merchantSelect.and("accountCode","like",new Object[]{"%"+merchantVo.getAccountCode()+"%"});
        }
        if(StringUtils.isNotBlank(merchantVo.getAccountName())){
            merchantSelect.and("accountName","like",new Object[]{"%"+merchantVo.getAccountName()+"%"});
        }
        if(StringUtils.isNotBlank(merchantVo.getAccountType())){
            merchantSelect.and("accountType",merchantVo.getAccountType());
        }
        if(StringUtils.isNotBlank(merchantVo.getNickName())){
            merchantSelect.and("nickName","like",new Object[]{"%"+merchantVo.getNickName()+"%"});
        }
        if(StringUtils.isNotBlank(merchantVo.getMemberName())){
            merchantSelect.and("memberName","like",new Object[]{"%"+merchantVo.getMemberName()+"%"});
        }
        merchantSelect.and("memberType", MemberType.MERCHANT.getCode());
        merchantSelect.orderBy("accountName").asc();
        PageList<Merchant> merchants = merchantSelect.pageList(merchantVo);
        List<MerchantVo> merchantVos = BeanKit.convert(MerchantVo.class, merchants);
        PageList<MerchantVo> result = new PageList<>(merchantVos,merchants.getPager());
        return result;
    }

    @Override
    public void add(MerchantVo merchantVo) {
        validateMerchantVo(merchantVo);
        //todo 将来需要添加账号密码
        Merchant merchant = BeanKit.convert(new Merchant(), merchantVo);
        merchant.setMemberType(MemberType.MERCHANT.getCode());
        merchant.setMemberCode(merchant.getMemberName());
        merchant.setMemberPassword(getPassWord(merchant.getMemberCode(),merchant.getMemberCode()));
        jdbcDao.insert(merchant);
    }

    @Override
    public boolean existMerchantName(MerchantVo merchantVo) {
        Select<Merchant> merchantSelect = jdbcDao.createSelect(Merchant.class).where("1", 1);
        merchantSelect.and("memberName", merchantVo.getMemberName());
        merchantSelect.and("memberType", MemberType.MERCHANT.getCode());
        if(merchantVo.getMemberId()!=null){
            merchantSelect.and("memberId","!=",new Object[]{merchantVo.getMemberId()});
        }
        Merchant merchant = merchantSelect.singleResult();
        if(merchant!=null){
            return true;
        }
        return false;
    }

    @Override
    public MerchantVo findById(Long memberId) {
        Merchant merchant = findPoById(memberId);
        return BeanKit.convert(new MerchantVo(), merchant);
    }

    private Merchant findPoById(Long memberId){
        Select<Merchant> merchantSelect = jdbcDao.createSelect(Merchant.class).where("1", 1);
        merchantSelect.and("memberId", memberId);
        return merchantSelect.singleResult();
    }

    @Override
    public void update(MerchantVo merchantVo) {
        validateMerchantVo(merchantVo);
        Merchant merchant = findPoById(merchantVo.getMemberId());
        mergeMerChant(merchant, merchantVo);
        jdbcDao.update(merchant);
    }

    @Override
    public void deleteByIds(Long[] memberIds) {
        Verifier.init().notEmpty(memberIds, "id").validate();
        for(int i=0;i<memberIds.length;i++){
            Select<ActivityEnroll> activityEnrollSelect = jdbcDao.createSelect(ActivityEnroll.class).where("1",1);
            activityEnrollSelect.and("memberId",memberIds[i]);
            ActivityEnroll activityEnroll = activityEnrollSelect.singleResult();
            if(activityEnroll!=null){
                throw new ImesneException("该商家存在报名单，无法删除");
            }
            Delete<Merchant> merchantDelete = jdbcDao.createDelete(Merchant.class).where("1",1);
            merchantDelete.and("memberId",memberIds[i]);
            merchantDelete.execute();
        }
    }

    @Override
    public boolean enable(Long memberId) {
        Merchant merchant = findPoById(memberId);
        merchant.setEnable(!merchant.isEnable());
        jdbcDao.update(merchant);
        return merchant.isEnable();
    }

    @Override
    public List<MerchantVo> nameFilter(MerchantVo merchantVo) {
        Select<Merchant> merchantSelect = jdbcDao.createSelect(Merchant.class).where("1", 1);
        merchantSelect.and("memberName", "like", new Object[]{"%" + merchantVo.getMemberName() + "%"});
        merchantSelect.orderBy("memberName").asc();
        PageList<Merchant> merchants = merchantSelect.pageList(merchantVo);
        List<MerchantVo> result = BeanKit.convert(MerchantVo.class,merchants);
        return result;
    }

    @Override
    public List<MerchantVo> nickNameFilter(MerchantVo merchantVo) {
        Select<Merchant> merchantSelect = jdbcDao.createSelect(Merchant.class).where("1", 1);
        merchantSelect.and("nickName", "like", new Object[]{"%" + merchantVo.getNickName() + "%"});
        merchantSelect.orderBy("nickName").asc();
        PageList<Merchant> merchants = merchantSelect.pageList(merchantVo);
        List<MerchantVo> result = BeanKit.convert(MerchantVo.class, merchants);
        return result;
    }

    @Override
    public MerchantVo logon(String memberCode, String memberPassword) {
        Verifier.init().notBlank(memberCode,"用户名").notBlank(memberPassword, "密码").validate();
        Select<Merchant> merchantSelect = jdbcDao.createSelect(Merchant.class);
        merchantSelect.and("memberCode",memberCode)
                        .and("type", MemberType.MERCHANT.getCode());
        Merchant merchant = merchantSelect.singleResult();
        if(merchant==null){
            throw new ImesneException("用户名或密码错误");
        }
        if(!merchant.isEnable()){
            throw new ImesneException("用户已被禁用");
        }
        if(!StringUtils.equals(merchant.getMemberCode(),getPassWord(memberCode,memberPassword))){
            throw new ImesneException("用户名或密码错误");
        }
        return BeanKit.convert(new MerchantVo(),merchant);
    }

    @Override
    public void modifyPwd(String memberCode, String oldPassword, String newPassword) {
        Verifier.init().notBlank(oldPassword,"旧密码").notBlank(newPassword, "新密码").validate();
        Select<Merchant> merchantSelect = jdbcDao.createSelect(Merchant.class);
        merchantSelect.and("memberCode",memberCode)
                .and("type", MemberType.MERCHANT.getCode());
        Merchant merchant = merchantSelect.singleResult();
        if(merchant==null){
            throw new ImesneException("当前用户不存在");
        }
        if(!StringUtils.equals(merchant.getMemberCode(),getPassWord(memberCode,oldPassword))){
            throw new ImesneException("旧密码错误");
        }
        merchant.setMemberPassword(getPassWord(memberCode,newPassword));
        jdbcDao.update(merchant);
    }

    private String getPassWord(String memberCode, String memberPassword) {
        return EncryptUtils.getMD5(Constants.PASSWORD_PREFIX + memberCode + memberPassword);
    }

    private void mergeMerChant(Merchant oldMerchant, MerchantVo newMerchantVo) {
        oldMerchant.setMemberName(newMerchantVo.getMemberName());
        oldMerchant.setNickName(newMerchantVo.getNickName());
        oldMerchant.setIntro(newMerchantVo.getIntro());
        oldMerchant.setServiceTel(newMerchantVo.getServiceTel());
        oldMerchant.setAccountType(newMerchantVo.getAccountType());
        oldMerchant.setAccountName(newMerchantVo.getAccountName());
        oldMerchant.setAccountCode(newMerchantVo.getAccountCode());
    }

    private void validateMerchantVo(MerchantVo merchantVo) {
        Verifier.init().notEmpty(merchantVo.getMemberName(),"商家名").notEmpty(merchantVo.getNickName(),"昵称")
                .notEmpty(merchantVo.getServiceTel(),"客服电话").notEmpty(merchantVo.getAccountType(),"账号类型")
                .notEmpty(merchantVo.getAccountName(),"账号名称").notEmpty(merchantVo.getAccountCode(), "账户号")
                .notEmpty(merchantVo.getIntro(), "商家简介");
        if(existMerchantName(merchantVo)){
            throw new ImesneException("商家名称重复");
        }
    }
}
